//影像检索
var maps = [];
// var historyMapInitExtent;
var initImageCompare;

var tiledMapServiceLayers0 = {};
var tiledMapServiceLayers1 = {};

var activeMap;
var clearActiveMapEvents;
var bindActiveMapEvents;

require([
    "esri/map", "esri/SpatialReference",
    "esri/layers/ArcGISDynamicMapServiceLayer",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "dojo/domReady!"
], function (Map, SpatialReference, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer) {

    initImageCompare = function () {
        const shanghaiSpatialRef = new SpatialReference({
            "wkt": 'PROJCS["shanghaicity",' + 'GEOGCS["GCS_Beijing_1954",' + 'DATUM["D_Beijing_1954",' + 'SPHEROID["Krasovsky_1940",6378245.0,298.3]],' + 'PRIMEM["Greenwich",0.0],' + 'UNIT["Degree",0.0174532925199433]],' + 'PROJECTION["Transverse_Mercator"],' + 'PARAMETER["False_Easting",-3457147.81],' + 'PARAMETER["False_Northing",0.0],' + 'PARAMETER["Central_Meridian",121.2751921],' + 'PARAMETER["Scale_Factor",1.0],' + 'PARAMETER["Latitude_Of_Origin",0.0],' + 'UNIT["Meter",1.0]]'
        });

        const historyMapInitExtent = new esri.geometry.Extent();
        historyMapInitExtent.xmin = -2000;
        historyMapInitExtent.xmax = 2000;
        historyMapInitExtent.ymin = -4000;
        historyMapInitExtent.ymax = 1000;
        historyMapInitExtent.setSpatialReference(shanghaiSpatialRef);

        //初始化对比用地图
        for (let i = 0; i < 2; i++) {
            const cmap = new Map("map_" + i, {
                extent: historyMapInitExtent,
                fitExtent: true,
                maxZoom: 9,
                minZoom: 0,
                logo: false,
                sliderPosition: "bottom-right",
            });

            maps.push(cmap);
        }

        //先使compareMap的div为show的状态，保证地图显示正常，然后再隐藏
        $("#compareMap").hide()
        $("#backBtn").show()
        $("#labelToggle").show()
        $(".compareMapLabel").show()


        T_LAYERS.forEach((item) => {
            const layerId = item.layerId;
            const url = item.url;
            const visible = item.visible;

            const tiledMapServiceLayer0 = new ArcGISTiledMapServiceLayer(url, {
                id: layerId,
                visible: visible
            });

            const tiledMapServiceLayer1 = new ArcGISTiledMapServiceLayer(url, {
                id: layerId,
                visible: visible
            });

            tiledMapServiceLayers0[layerId] = tiledMapServiceLayer0;
            tiledMapServiceLayers1[layerId] = tiledMapServiceLayer1;

            if (layerId === "zhuji" || layerId === "zhuji1979" || layerId === "zhuji1948") {
                return
            }

            const div0 = $(`<div id="${layerId}_0" class="sub_item">${layerId}</div>`)
            $("#compareMapPanel0").append(div0);
            const div1 = $(`<div id="${layerId}_1" class="sub_item">${layerId}</div>`)
            $("#compareMapPanel1").append(div1);

            $("#" + layerId + "_0").click((e) => {
                maps[0].removeAllLayers();
                maps[0].addLayer(tiledMapServiceLayers0[layerId]);

                if (layerId === "1948") {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji1948"]);
                } else if (layerId === "1979") {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji1979"]);
                } else {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji"]);
                }

                // $("#label_0").text(layerId + "年影像");
                if (layerId !== "政务地图") {
                    $("#label_0").text(layerId + "年影像");
                } else {
                    $("#label_0").text("政务地图");
                }

                $("#compareMapPanel0").css("display", "none");

            })

            $("#" + layerId + "_1").click((e) => {
                maps[1].removeAllLayers();
                maps[1].addLayer(tiledMapServiceLayers1[layerId]);
                if (layerId === "1948") {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji1948"]);
                } else if (layerId === "1979") {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji1979"]);
                } else {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);
                }
                // maps[0].getLayer(layerId).visible=true;

                if (layerId !== "政务地图") {
                    $("#label_1").text(layerId + "年影像");
                } else {
                    $("#label_1").text("政务地图");
                }

                $("#compareMapPanel1").css("display", "none");

            })
        })

        // // 默认加载1948和最新
        // maps[0].addLayer(tiledMapServiceLayers0["2021"]);
        // maps[1].addLayer(tiledMapServiceLayers1["2021"]);
        // maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);

        // //解决先加载1948影像，导致map0最大级别只有8的问题
        // const timeout = setTimeout(() => {
        //     maps[0].addLayer(tiledMapServiceLayers0["1948"]);
        //     maps[0].removeLayer(tiledMapServiceLayers0["2021"]);
        //     maps[0].addLayer(tiledMapServiceLayers0["zhuji1948"]);

        //     clearTimeout(timeout)
        // }, 1000);


        // $("#label_0").text("1948年影像");
        // $("#label_1").text("2021年影像");


        maps[0].addLayer(tiledMapServiceLayers0["2021"]);
        maps[1].addLayer(tiledMapServiceLayers1["2006"]);
        maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);
        maps[0].addLayer(tiledMapServiceLayers0["zhuji"]);

        $("#label_0").text("2021年影像");
        $("#label_1").text("2006年影像");

        $("#compareMapLabel0").click(function () {
            if ($("#compareMapPanel0").css("display") === "none") {
                $("#compareMapPanel0").css("display", "flex");
            } else {
                $("#compareMapPanel0").css("display", "none");
            }
        });

        $("#compareMapLabel1").click(function () {
            if ($("#compareMapPanel1").css("display") === "none") {
                $("#compareMapPanel1").css("display", "flex");
            } else {
                $("#compareMapPanel1").css("display", "none");
            }
        });

        $("#labelToggle").click(function () {
            var text = $("#labelToggle").text().trim()
            if (text === "开启注记") {
                $("#labelToggle").text("隐藏注记")
                if ($("#label_0").text() === "1948年影像") {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji1948"]);
                } else if ($("#label_0").text() === "1979年影像") {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji1979"]);
                } else {
                    maps[0].addLayer(tiledMapServiceLayers0["zhuji"]);
                }

                if ($("#label_1").text() === "1948年影像") {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji1948"]);
                } else if ($("#label_1").text() === "1979年影像") {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji1979"]);
                } else {
                    maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);
                }

            } else if (text === "隐藏注记") {
                $("#labelToggle").text("开启注记")
                if ($("#label_0").text() === "1948年影像") {
                    maps[0].removeLayer(tiledMapServiceLayers0["zhuji1948"]);
                } else if ($("#label_0").text() === "1979年影像") {
                    maps[0].removeLayer(tiledMapServiceLayers0["zhuji1979"]);
                } else {
                    maps[0].removeLayer(tiledMapServiceLayers0["zhuji"]);
                }

                if ($("#label_1").text() === "1948年影像") {
                    maps[1].removeLayer(tiledMapServiceLayers1["zhuji1948"]);
                } else if ($("#label_1").text() === "1979年影像") {
                    maps[1].removeLayer(tiledMapServiceLayers1["zhuji1979"]);
                } else {
                    maps[1].removeLayer(tiledMapServiceLayers1["zhuji"]);
                }
            }
        });

        $("#backBtn").click(function () {
            $("#mainMap").show();
            $("#compareMap").hide();
            maps[0].removeAllLayers();
            maps[1].removeAllLayers();

            // maps[0].addLayer(tiledMapServiceLayers0["1948"]);
            // maps[1].addLayer(tiledMapServiceLayers1["2021"]);
            // maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);
            // maps[0].addLayer(tiledMapServiceLayers0["zhuji1948"]);
            // $("#label_0").text("1948年影像");
            // $("#label_1").text("2021年影像");

            maps[0].addLayer(tiledMapServiceLayers0["2021"]);
            maps[1].addLayer(tiledMapServiceLayers1["2006"]);
            maps[1].addLayer(tiledMapServiceLayers1["zhuji"]);
            maps[0].addLayer(tiledMapServiceLayers0["zhuji"]);
    
            $("#label_0").text("2021年影像");
            $("#label_1").text("2006年影像");

            $("#labelToggle").text("隐藏注记")

            //初始化范围
            // maps[0].setExtent(historyMapInitExtent, true);

        });

        //地图联动事件，每次切换活动地图时，重新绑定联动事件，防止非活动地图的范围变化触发联动事件
        var activeMapEventHandlers = [];
        var isZoomOrPan = false

        maps.forEach(function (map) {
            map.on("pan-start", function (evt) { //鼠标在哪个地图上，该地图就是激活地图
                if (!isZoomOrPan) {
                    activeMap = map;

                    isZoomOrPan = true
                    clearActiveMapEvents();
                    bindActiveMapEvents();
                } else {
                    isZoomOrPan = false
                }
            });

            map.on("zoom-start", function (evt) { //鼠标在哪个地图上，该地图就是激活地图
                if (!isZoomOrPan) {
                    activeMap = map;

                    isZoomOrPan = true
                    clearActiveMapEvents();
                    bindActiveMapEvents();
                } else {
                    isZoomOrPan = false
                }
            });

            // map.on("mourse-over", function (evt) { //鼠标在哪个地图上，该地图就是激活地图
            //     if(!isZoomOrPan){
            //     activeMap = map;

            //         isZoomOrPan=true
            //         clearActiveMapEvents();
            //         bindActiveMapEvents();
            //     }else{
            //         isZoomOrPan=false
            //     }
            // });
        });


        clearActiveMapEvents = function () {
            activeMapEventHandlers.forEach(function (eventHandler) {
                eventHandler.remove();
            });
            activeMapEventHandlers = [];
        }

        bindActiveMapEvents = function () {
            //放大联动
            activeMapEventHandlers.push(activeMap.on("zoom-end", function (evt) {
                maps.forEach(function (map) {
                    if (map != activeMap) {
                        map.setExtent(evt.extent);
                        isZoomOrPan = false
                    }
                });
            }));
            //平移联动
            activeMapEventHandlers.push(activeMap.on("pan-end", function (evt) {
                maps.forEach(function (map) {
                    if (map != activeMap) {
                        map.setExtent(evt.extent);
                        isZoomOrPan = false
                    }
                });
            }));
        }
    }

    initImageCompare()
});

// function compareMapsReset() {
//     //初始化
//     //maps清空图层、div隐藏、drawGraphics、compareDrawGraphicsLayers清空
//     for (var i = 0; i < 6; i++) {
//         maps[i].removeAllLayers();
//         $("#map_" + i).hide();
//         maps[i].setExtent(historyMapInitExtent);
//     }
// }